#!/usr/bin/env bash

###
### This is a script for setting up the public key files
### on servers so that users don't have to type their
### passwords over and over each time they login. 
###

algorithm="dsa"
username=$(whoami) 

function usage() {
    echo "Usage: trustme [username] <[username@]hostname> [rsa|dsa]";
    exit 0;
}

function trust() {
    local username="${1}"
    local hostname="${2}"
    local algorithm="${3}"
    
    if [ ! -f $HOME/.ssh/id_$algorithm ]; then 
        ssh-keygen -t $algorithm -P '' -N '' -f $HOME/.ssh/id_$algorithm
    fi
    
    echo "Sending $HOME/.ssh/id_$algorithm.pub to ${hostname}"
    scp $HOME/.ssh/id_$algorithm.pub $username@$hostname:"~/id_$algorithm.pub"
    
    echo "Requesting trust from ${hostname}"
    ssh $username@$hostname "mkdir -p ~/.ssh; 
chmod 700 ~/.ssh; 
cat ~/id_$algorithm.pub >> ~/.ssh/authorized_keys; 
chmod 644 ~/.ssh/authorized_keys; 
rm -f ~/id_$algorithm.pub;"
}

if [ $# -gt 2 ]; then 
    username="${1}"
    hostname="${2}"
    algorithm="${3}"
elif [ $# -gt 1 ]; then 
    username="${1}"
    hostname="${2}"
elif [ $# == 1 ]; then 
    if [ "${1}" == "--help" ]; then
        usage;
        exit;
    fi
    #if [[ "${1}" =~ .*@.* ]]; then
    #    echo "hi"
        #IFS=@
        #echo "${1}" | read username hostname
        #IFS=.
    #else
        hostname="${1}"
    #fi
else 
    usage;
fi

trust ${username} ${hostname} ${algorithm};


exit 0;
